package utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.Security;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class SignatureUtil {
    /**
     * 签名
     * @param params
     * @param signKey
     * @return
     */
    public static String sign(Map<String, String> params, String signKey) {
        SortedMap<String, String> sortedMap = new TreeMap<>(params);

        StringBuilder toSign = new StringBuilder();
        for (String key : sortedMap.keySet()) {
            String value = params.get(key);
            if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) {
                toSign.append(key).append("=").append(value).append("&");
            }
        }

        //加上商户秘钥  注册签名串
        toSign.append("key=").append(signKey);
        System.out.println("signStr : " + toSign.toString());
        return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
    }

    /**
     * 校验签名
     * @param params
     * @param signKey
     * @return
     */
    public static Boolean verify(Map<String, String> params, String signKey) {
        String sign = sign(params, signKey);
        return sign.equals(params.get("sign"));
    }

    public static String decryptData(byte[] b, SecretKeySpec key) throws Exception {
        Cipher cipher = null;
        Security.addProvider(new BouncyCastleProvider());
        cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(b), "utf-8");
    }

    public static SecretKeySpec md5Key(String appKey){
        return new SecretKeySpec(Md5Util.MD5Encode(appKey,"utf-8").toLowerCase().getBytes(), "AES");
    }

    public static byte[] base64Decode(String reqInfo) throws IOException {
        return Base64.decode(reqInfo);
    }
}
